<?php

namespace App\Http\Controllers\Admin\Wechat\Fun\Reply;

use Illuminate\Http\Request;
use App\Http\Controllers\AdminController;


use App\Models\Wechat\Keyword;
use App\Models\Wechat\Reply;
use DB;
use Validator;

class KeywordController extends AdminController
{
    /**
     * 获取列表
     * @return [type] [description]
     */
    function getLists(Request $request){
        $size = 10 ;
        $where  = [] ;
        $page   = $request->input('page') ? $request->input('page') : 1;
        $start  = ($page-1)*$size;
        $query = DB::table('wechat_keyword')
                ->select('wechat_keyword.id','wechat_keyword.ruleName','wechat_keyword.keyword','wechat_reply.replyType')
                ->leftJoin('wechat_reply','wechat_keyword.id','=','wechat_reply.wechat_keyword_id');
        $search = $request->input('search');
        if($search){
            $query = $query->where('wechat_keyword.ruleName','like',"$search%")->orWhere('wechat_keyword.keyword','like',"$search%");
        }
        $list['total'] = $query->count();
        if($list['total']>0){
            $list['result'] = $query->orderBy('wechat_keyword.created_at','desc')->skip($start)->take($size)->get();
        }
        $this->ajaxJson(0,'',$list);
    }

    /**
     * 获取单个数据
     * @return [type] [description]
     */
    function getOne($id){
        $keyword = $this->_get_one($id);
        $keyword->reply;
        $this->ajaxJson(0,'',$keyword);
    }

	/**
	 * 更新关键词回复
	 * @return [type] [description]
	 */
    function updateKeyword(Request $request){
    	//基本数据验证
    	$validator = $this->formValidator($request->all());
        if($validator->fails()){
            $this->ajaxJson(1,$validator->errors()->first());
        }
        //唯一验证
    	$this->_check_unique_keyword($request->input('keyword'),$request->input('id'));
    	//数据存在验证
    	$keyword_id = $request->input('id');
    	if($keyword_id){
    		$this->_get_one($keyword_id);
    	}
		$replyType        = $request->input('replyType');
		$wechat_mpnews_id = $request->input('wechat_mpnews_id');
		$wechat_text_id   = $request->input('wechat_text_id');
		$wechat_image_id  = $request->input('wechat_image_id');
    	if($replyType=='mpnews'){
    		$mpnews = DB::table('wechat_mpnews')->find($wechat_mpnews_id);
    		if(!$mpnews){
    			$this->ajaxJson(1,'要添加的图文回复项已不存在,请重新选择');
    		}
    	}
    	if($replyType=='text'){
    		$text = DB::table('wechat_text')->find($wechat_text_id);
    		if(!$text){
    			$this->ajaxJson(1,'要添加的文本回复项已不存在,请重新选择');
    		}
    	}
    	if($replyType=='image'){
    		$image = DB::table('wechat_image')->find($wechat_image_id);
    		if(!$image){
    			$this->ajaxJson(1,'要添加的图片回复项已不存在,请重新选择');
    		}
    	}

    	$keywordData = [
			'ruleName'   => $request->input('name'),
			'keyword'    => $request->input('keyword'),
			'updated_at' => date('Y-m-d H:i:s'),
    	];

    	$replyData = [
			'replyType'        => $replyType,
			'wechat_text_id'   => $wechat_text_id,
			'wechat_image_id'  => $wechat_image_id,
			'wechat_mpnews_id' => $wechat_mpnews_id,
			'updated_at'       => date('Y-m-d H:i:s'),
    	];

        $reply = new Reply();
    	try {
    		DB::beginTransaction();
    		if(!$keyword_id){
				$keywordData['created_at']      = $replyData['created_at'] = date('Y-m-d H:i:s');
				$keyword_id                     = DB::table('wechat_keyword')->insertGetId($keywordData);
				$replyData['wechat_keyword_id'] = $keyword_id;
    			DB::table('wechat_reply')->insert($replyData);
    		}else{
    			DB::table('wechat_keyword')->where('id',$keyword_id)->update($keywordData);
    			DB::table('wechat_reply')->where('wechat_keyword_id',$keyword_id)->update($replyData);
    		}
    		DB::commit();
            $reply->cacheEmpty($keyword_id);
            $this->ajaxJson(0,'更新成功');
    	} catch (Exception $e) {
    		DB::rollBack();
            Log::error('【'.$e->getMessage().'】'.'【'.$e->getFile().'】'.'【'.$e->getTraceAsString ().'】');
            $this->ajaxJson(1,'更新失败');
    	}
    }

    /**
     * 验证关键词唯一
     * @return [type] [description]
     */
    function checkUniqueKeyword(Request $request){
    	$this->_check_unique_keyword($request->input('keyword'),$request->input('id'));
    	$this->ajaxJson(0,'');
    }

    /**
     * 删除关键词
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    function deleteKeyword($id){
        $this->_get_one($id);
        $reply = new Reply();
        try {
            DB::beginTransaction();
            DB::table('wechat_keyword')->where('id',$id)->delete();
            DB::table('wechat_reply')->where('wechat_keyword_id',$id)->delete();
            DB::commit();
            $reply->cacheEmpty($id);
            $this->ajaxJson(0,'删除成功');
        } catch (Exception $e) {
            DB::rollBack();
            Log::error('【'.$e->getMessage().'】'.'【'.$e->getFile().'】'.'【'.$e->getTraceAsString ().'】');
            $this->ajaxJson(1,'删除失败');
        }
    }

    /**
     * 表单验证
     * @param  array  $data [description]
     * @return [type]       [description]
     */
    private function formValidator(array $data){
        $attribute =  array(
			'name'             => '规则名',
			'keyword'          => '关键词',
			'replyType'        => '回复内容',
			'wechat_text_id'   => '文本内容',
			'wechat_image_id'  => '图片内容',
			'wechat_mpnews_id' => '图文内容',
        );

        $message  = array(
            'required' => ':attribute必须填写',
            'in' => ':attribute数据错误,必须是 mpnews,image,text其中的一个',
            'required_if' => '您选择了:attribute却未指定数据,请求失败'
        );

        return Validator::make($data, [
			'name'      => 'bail|required',
			'keyword'   => 'bail|required',
			'replyType' => 'bail|required|in:mpnews,image,text',
			'wechat_text_id' => 'required_if:replyType,text|numeric',
			'wechat_image_id' => 'required_if:replyType,image|numeric',
			'wechat_mpnews_id' => 'required_if:replyType,mpnews|numeric',
        ],$message,$attribute);
    }

    private function _get_one($id){
    	$keyword = Keyword::find($id);
    	if(!$keyword){
    		$this->ajaxJson(1,'未知数据');
    	}
    	return $keyword;
    }

    /**
     * 公共验证关键词唯一
     * @param  [type] $keyword [description]
     * @param  [type] $id      [description]
     * @return [type]          [description]
     */
    private function _check_unique_keyword($keyword,$id){
    	$count = Keyword::where('id','!=',$id)->where('keyword',$keyword)->count();
    	if($count>0){
    		$this->ajaxJson(1,'存在相同的关键词,请更换');
    	}
    	return true;
    }
}
